import { http } from '@kit.NetworkKit'
import { UserInfo } from '../entity/UserInfo'
import { PersistenceV2 } from '@kit.ArkUI'

let request = http.createHttp()
let userInfo:UserInfo =  PersistenceV2.globalConnect({type:UserInfo,defaultCreator:() => new UserInfo()})
export function post<T>(url:string, params?:Object):Promise<T> {
  return new Promise<T>((resolve, reject) => {
    let headers = {"Content-Type": "application/json"}
    if(userInfo.token){
      headers['X-Hioshop-ToKen'] = userInfo.token
    }
    request.request(url, {
      method:http.RequestMethod.POST,
      header:headers,
      extraData:params,

    }).then((r) => {
      if (r.responseCode == 200) {
          resolve(JSON.parse(r.result as string))
      } else {
        reject(new Error(`网络错误：${r.responseCode}`))
      }
    })
      .catch((e:Error) => {
        reject(e)
      })
  })
}

export function get<T>(url:string,params?:Object):Promise<T> {
  return new Promise<T>((resole, reject) => {
    if (params) {
      url += '?' + Object.keys(params).map((k) => `${k}=${params[k]}`).join('&')
    }
    let headers = {}
    if(userInfo.token){
      headers['X-Hioshop-ToKen'] = userInfo.token
    }
    request.request(url, {
      method:http.RequestMethod.GET,
      header:headers

    })
      .then((res) => {
        if (res.responseCode == 200) {
          let t:T = JSON.parse(res.result as string)
          resole(t)
        } else {
          reject(new Error(`网络错误：${res.responseCode}`))
        }
      })
      .catch(e => reject(e))
  })
}